import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useDeviceStore = defineStore('device', () => {
  const currentDevice = ref(null)
  
  function setCurrentDevice(device) {
    currentDevice.value = device
    // 保存到 localStorage，这样刷新页面后还能保持状态
    if (device) {
      localStorage.setItem('currentDevice', JSON.stringify(device))
    } else {
      localStorage.removeItem('currentDevice')
    }
  }

  // 初始化时从 localStorage 恢复状态
  function initialize() {
    const savedDevice = localStorage.getItem('currentDevice')
    if (savedDevice) {
      try {
        currentDevice.value = JSON.parse(savedDevice)
      } catch (e) {
        localStorage.removeItem('currentDevice')
      }
    }
  }

  return {
    currentDevice,
    setCurrentDevice,
    initialize
  }
})
